package com.wcj.sort;

public class 推排序 {


    public static void main(String[] args) {
        int[] arr = new int[]{23,12,36,451,2,89,78,54};
        heapSort(arr);
        for (int i : arr) {
            System.out.println(i);
        }
    }

    public static void heapSort(int[] arr){
        buildSort(arr);
        for (int i = arr.length - 1; i > 0; i--){
            int tmp = arr[0];
            arr[0] = arr[i];
            arr[i] = tmp;
            percDown(arr,0,i);
        }
    }

    /**
     * 构建堆
     * @param arr
     * @return
     */
    public static void buildSort(int[] arr){
        for (int i = arr.length/2 - 1; i >= 0; i--)
            percDown(arr,i, arr.length);
    }

    /**
     * 下滤元素
     * @param arr
     * @param i
     * @param end
     */
    public static void percDown(int[] arr,int i, int end){
        // 要交换的儿子
        int child;
        int tmp;
        for (tmp = arr[i]; leftChild(i) < end; i = child){
            child = leftChild(i);
            //找出最小儿子
            if (child != end - 1 && arr[child] < arr[child + 1]){
                child++;
            }
            if (tmp < arr[child]){
                arr[i] = arr[child];
            }else {
                break;
            }
        }
        arr[i] = tmp;
    }

    /**
     * 获取左孩子
     * @param i
     * @return
     */
    public static int leftChild(int i){
        return 2*i+1;
    }
}
